package org.smartboot.flow.core.parser;

import org.smartboot.flow.core.util.AssertUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author qinluo
 * @date 2022/11/19 14:29
 * @since 1.0.0
 */
@SuppressWarnings("unchecked")
public class DefaultObjectCreator implements ObjectCreator {

    private static final ObjectCreator INSTANCE = new DefaultObjectCreator();

    private final Map<Class<?>, Object> cachedObjects = new ConcurrentHashMap<>();

    private static <T> Class<T> check(String type) {
        try {
            return (Class<T>) Class.forName(type);
        } catch (Exception e) {
            return null;
        }
    }

    public static ObjectCreator getInstance() {
        return INSTANCE;
    }

    @Override
    public <T> T create(String typename, boolean useCache) {
        AssertUtil.notBlank(typename, "type must not be blank!");
        Class<T> type = check(typename);
        AssertUtil.notNull(type, "typename " + typename + " is not class");

        T created = null;
        if (useCache) {
            created = (T) cachedObjects.get(type);
        }

        if (created != null) {
            return created;
        }

        try {
            created = type.newInstance();
            cachedObjects.put(type, created);
            return created;
        } catch (Exception e) {
            throw new IllegalStateException(type.getName(), e);
        }
    }
}
